package com.neusoft.mid.msf.common.handler;

import com.neusoft.mid.msf.common.constant.ApiCode;
import com.neusoft.mid.msf.common.constant.CommonContants;
import com.neusoft.mid.msf.common.exception.BaseException;
import com.neusoft.mid.msf.common.msg.BaseResponse;
import com.neusoft.mid.msf.common.msg.auth.TokenErrorResponse;
import com.neusoft.mid.msf.common.msg.auth.TokenExpiredResponse;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: pangu
 * @description: 框架的全局异常处理类
 * @author: fengjd
 * @create: 2022-07-26 10:57
 **/

@ControllerAdvice("com.neusoft.mid")
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * API调用异常处理
     * @param request
     * @param response
     * @param ex
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public BaseResponse baseExceptionHander(HttpServletRequest request, HttpServletResponse response, BaseException ex){
        log.error(ex.getMessage(), ex);
        request.setAttribute(CommonContants.EXCEPTION_ATTRIBUTE_NAME,ex);
        return new BaseResponse(ex.getStatus(), ex.getMessage());
    }


    /**
     * Token 过期的异常处理
     * @param request
     * @param response
     * @param ex
     * @return
     */
    @ExceptionHandler({ExpiredJwtException.class})
    public BaseResponse userTokenExpiredJwtException(HttpServletRequest request, HttpServletResponse response, ExpiredJwtException ex){
        log.error(ex.getMessage(), ex);
        request.setAttribute(CommonContants.EXCEPTION_ATTRIBUTE_NAME,ex);
        return new TokenExpiredResponse();
    }

    /**
     * token签名错误的异常处理
     * @param request
     * @param response
     * @param ex
     * @return
     */
    @ExceptionHandler({SignatureException.class})
    public BaseResponse userTokenSignatureException(HttpServletRequest request, HttpServletResponse response, SignatureException ex){
        log.error(ex.getMessage(), ex);
        request.setAttribute(CommonContants.EXCEPTION_ATTRIBUTE_NAME,ex);
        return new TokenErrorResponse();
    }

    @ExceptionHandler({Exception.class})
    public BaseResponse otherExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex){
        log.error(ex.getMessage(), ex);
        request.setAttribute(CommonContants.EXCEPTION_ATTRIBUTE_NAME,ex);
        return  new BaseResponse(ApiCode.STATUS_FAILED.getCode(),ApiCode.STATUS_FAILED.getName());
    }

}
